<template>
  <div class="venue-list">
    <div class="page-header">
      <div class="header-title">
        <h2>场地列表</h2>
        <span class="subtitle">管理所有可用场地</span>
      </div>
      <div class="header-actions">
        <el-button type="primary" icon="el-icon-plus" @click="handleAddVenue">添加场地</el-button>
      </div>
    </div>

    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="场地名称">
          <el-input v-model="filterForm.name" placeholder="请输入场地名称" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <el-table
        :data="venueList"
        style="width: 100%"
        border
        v-loading="loading"
        @selection-change="handleSelectionChange">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="name" label="场地名称">
          <template slot-scope="scope">
            <el-link type="primary" @click="viewVenueDetail(scope.row)">{{ scope.row.name }}</el-link>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="" label="类型">
          <template slot-scope="scope">
            <template v-if="scope.row.type">
              <el-tag 
                v-for="(type, index) in scope.row.type.split(',')" 
                :key="index"
                :type="getTypeTag(type.trim())"
                style="margin-right: 5px; margin-bottom: 5px;">
                {{ getTypeText(type.trim()) }}
              </el-tag>
            </template>
            <span v-else>-</span>
          </template>
        </el-table-column> -->
        <el-table-column prop="tags" label="类型">
          <template slot-scope="scope">
            <template v-if="scope.row.tags">
              <el-tag 
                v-for="(tag, index) in scope.row.tags.split(',')" 
                :key="index"
                :type="getTagType(index)"
                style="margin-right: 5px; margin-bottom: 5px;">
                {{ tag.trim() }}
              </el-tag>
            </template>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="capacity" label="容纳人数" width="100"></el-table-column> -->
        <!-- <el-table-column prop="location" label="位置"></el-table-column> -->
        <el-table-column prop="createTime" label="创建时间">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : scope.row.status === 0 ? 'warning' : 'danger'">
              {{ scope.row.status === 1 ? '可用' : scope.row.status === 0 ? '维护中' : '已禁用' }}
            </el-tag>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="viewVenueDetail(scope.row)">查看详情</el-button>
            <!-- <el-button type="text" size="small" @click="editVenue(scope.row)">编辑</el-button> -->
            <!-- <el-button 
              type="text" 
              size="small" 
              :class="{ 'danger-button': scope.row.status === 1 }"
              @click="toggleVenueStatus(scope.row)">
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button> -->
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 场地详情对话框 -->
    <el-dialog title="场地详情" :visible.sync="venueDetailVisible" width="70%">
      <div v-if="currentVenue" class="venue-detail">
        <div class="venue-header">
          <h3>{{ currentVenue.name }} - 预约记录</h3>
        </div>
        
        <div class="detail-section">
          <el-table :data="venueBookings" style="width: 100%" v-loading="bookingsLoading">
            <el-table-column prop="activity.title" label="活动名称"></el-table-column>
            <el-table-column prop="activity.maxParticipants" label="活动最大人数"></el-table-column>
            <el-table-column label="活动开始时间">
              <template slot-scope="scope">
                {{ formatDateTime(scope.row.beginTime) }}
              </template>
            </el-table-column>
            <el-table-column label="持续时间">
              <template slot-scope="scope">
                {{ scope.row.duration/60 }} 小时
              </template>
            </el-table-column>
            <el-table-column label="活动类型">
              <template slot-scope="scope">
                <template v-if="scope.row.activity.tags">
                  <el-tag 
                    v-for="(tag, index) in scope.row.activity.tags.split(',')" 
                    :key="index"
                    :type="getTagType(index)"
                    style="margin-right: 5px; margin-bottom: 5px;">
                    {{ tag.trim() }}
                  </el-tag>
                </template>
                <span v-else>-</span>
              </template>
            </el-table-column>
          </el-table>
          <!-- <div v-if="venueBookings.length === 0" class="empty-data">
            <i class="el-icon-date"></i>
            <p>暂无预约记录</p>
          </div> -->
        </div>
      </div>
    </el-dialog>

    <!-- 编辑场地对话框 -->
    <el-dialog title="添加场地" :visible.sync="editDialogVisible" width="50%">
      <el-form :model="venueForm" :rules="venueRules" ref="venueForm" label-width="100px">
        <el-form-item label="场地名称" prop="name">
          <el-input v-model="venueForm.name"></el-input>
        </el-form-item>
        <el-form-item label="场地标签" prop="tags">
          <el-input v-model="venueForm.tags" placeholder="多个标签请用英文逗号分隔，如：教室,阶梯教室"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitVenueForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import httpInstance from "@/utils/http";

export default {
  name: 'VenueList',
  data() {
    return {
      loading: false,
      filterForm: {
        name: ''
      },
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      venueList: [],
      selectedRows: [],
      venueDetailVisible: false,
      currentVenue: null,
      editDialogVisible: false,
      dialogTitle: '添加场地',
      venueForm: {
        id: '',
        name: '',
        tags: ''
      },
      venueBookings: [], // 添加场地预约记录数组
      bookingsLoading: false, // 添加加载状态
      venueRules: {
        name: [
          { required: true, message: '请输入场地名称', trigger: 'blur' }
        ],
        tags: [
          { required: true, message: '请输入场地标签', trigger: 'blur' }
        ]
      },
      type: [
        { required: true, message: '请选择场地类型', trigger: 'change' }
      ],
      capacity: [
        { required: true, message: '请输入容纳人数', trigger: 'blur' }
      ],
      location: [
        { required: true, message: '请输入场地位置', trigger: 'blur' }
        ]
      
    }
         
  },
  created() {
    // 检查token是否存在
    const token = localStorage.getItem('token')
    if (!token) {
      this.$router.push('/admin/login')
    }
    
    this.fetchVenueList();
  },
    methods: {
    getTagType(index) {
      // 循环使用不同的标签类型
      const types = ['', 'success', 'info', 'warning', 'danger'];
      return types[index % types.length];
    },
    fetchVenueList() {
      this.loading = true;
      
      const params = {
        name: this.filterForm.name || undefined
      };
      
      Object.keys(params).forEach(key => params[key] === undefined && delete params[key]);
      
      // 调用后端接口获取场地列表
      httpInstance.get('/api/venue/list')
        .then(res => {
          if (res.code === 200) {
            this.venueList = res.data;
            
            // 过滤数据
            if (params.name) {
              this.venueList = this.venueList.filter(venue => 
                venue.name.toLowerCase().includes(params.name.toLowerCase())
              );
            }
            
            this.pagination.total = this.venueList.length;
          } else {
            this.$message.error(res.msg || '获取场地列表失败');
          }
        })
        .catch(err => {
          console.error('获取场地列表失败:', err);
          this.$message.error('获取场地列表失败，请稍后重试');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    resetForm() {
      this.filterForm = {
        name: ''
      };
      this.fetchVenueList();
    },
    
    handleSearch() {
      this.pagination.currentPage = 1;
      this.fetchVenueList();
    },
    
    resetForm() {
      this.filterForm = {
        name: '',
        type: '',
        status: ''
      };
      this.fetchVenueList();
    },
    
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },
    
    viewVenueDetail(venue) {
      this.currentVenue = {
        ...venue,
        status: venue.status === 1 ? '可用' : venue.status === 0 ? '维护中' : '已禁用',
        createTime: this.formatDate(venue.createTime)
      };
      
      this.venueBookings = [];
      this.bookingsLoading = true;
      this.venueDetailVisible = true;
      
      // 调用后端接口获取场地预约记录
      httpInstance.post(`/api/venue/bookingList/${venue.id}`)
        .then(res => {
          if (res.code === 200) {
            this.venueBookings = res.data || [];
          } else {
            this.venueBookings = [];
            this.$message.error(res.msg || '获取预约记录失败');
          }
        })
        .catch(err => {
          console.error('获取预约记录失败:', err);
          this.venueBookings = [];
          this.$message.error('获取预约记录失败，请稍后重试');
        })
        .finally(() => {
          this.bookingsLoading = false;
        });
    },
    
    handleAddVenue() {
      this.venueForm = {
        name: '',
        tags: ''
      };
      this.editDialogVisible = true;
    },
    
    submitVenueForm() {
      this.$refs.venueForm.validate(async (valid) => {
        if (valid) {
          try {
            // 添加场地逻辑
            const response = await httpInstance.post('/api/venue', this.venueForm);
            
            if (response && response.code === 200) {
              this.$message.success('添加成功');
              this.editDialogVisible = false;
              this.fetchVenueList();
            } else {
              this.$message.error(response?.msg || '添加失败');
            }
          } catch (error) {
            console.error('添加场地失败:', error);
            this.$message.error('添加失败，请稍后重试');
          }
        } else {
          return false;
        }
      });
    },
    
    editVenue(venue) {
      this.dialogTitle = '编辑场地';
      this.venueForm = {
        id: venue.id,
        name: venue.name,
        tags: venue.tags
      };
      this.editDialogVisible = true;
    },
    
    handleAddVenue() {
      this.dialogTitle = '添加场地';
      this.venueForm = {
        id: '',
        name: '',
        type: 'indoor',
        capacity: 100,
        location: '',
        description: '',
        facilities: '',
        status: 1
      };
      this.editDialogVisible = true;
    },
    toggleVenueStatus(venue) {
      const action = venue.status === 1 ? '禁用' : '启用';
      const newStatus = venue.status === 1 ? 2 : 1;
      
      this.$confirm(`确定要${action}该场地吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: venue.status === 1 ? 'warning' : 'info'
      }).then(() => {
        // 模拟API调用
        setTimeout(() => {
          this.$message.success(`${action}成功`);
          this.fetchVenueList();
        }, 500);
      }).catch(() => {
        // 取消操作
      });
    },
    
    handleSizeChange(size) {
      this.pagination.pageSize = size;
      this.fetchVenueList();
    },
    
    handleCurrentChange(page) {
      this.pagination.currentPage = page;
      this.fetchVenueList();
    },
    
    getTypeTag(type) {
      const typeMap = {
        'indoor': 'success',
        'outdoor': 'warning',
        'multi': 'primary'
      };
      return typeMap[type] || '';
    },
    
    getTypeText(type) {
      const typeMap = {
        'indoor': '室内',
        'outdoor': '室外',
        'multi': '多功能'
      };
      return typeMap[type] || type;
    },
    
    formatDateTime(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
    },
    
    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    }
  }
}
</script>

<style scoped>
.venue-list {
  padding-bottom: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  display: flex;
  flex-direction: column;
}

.header-title h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.subtitle {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.filter-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.danger-button {
  color: #F56C6C;
}

.detail-section {
  margin-top: 30px;
}

.detail-section h3 {
  font-size: 16px;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  color: #303133;
}

/* 确保对话框内容可滚动 */
.el-dialog__body {
  max-height: 60vh;
  overflow-y: auto;
}

.empty-data {
  text-align: center;
  padding: 30px 0;
  color: #909399;
}

.empty-data i {
  font-size: 40px;
  margin-bottom: 10px;
}

/* 场地图片展示样式 */
.venue-images {
  margin-bottom: 20px;
}

.venue-image-container {
  width: 100%;
}

.venue-image-wrapper {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  overflow: hidden;
  background-color: #f5f7fa;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10px;
}

.venue-image {
  width: 100%;
  max-height: 300px;
  object-fit: cover;
  border-radius: 4px;
}

h4 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 16px;
  color: #606266;
}
.venue-header {
  margin-bottom: 20px;
  border-bottom: 1px solid #EBEEF5;
  padding-bottom: 15px;
}

.venue-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}
</style>